package org.infosec.lc.exercises.ObjectNetworkTransmission.code.castor;

import java.io.IOException;
import java.io.StringWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;
import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.IdentityCard;
import org.infosec.lc.exercises.ObjectNetworkTransmission.modle.Person;

/**
	文件名：CastorUDPSend.java
	作  者：林超
	时  间：2011-7-20下午02:38:34

	功能描述：构建xml,并以UDP形式在网络中传输
	
	pom.xml	:
			
 */
public class CastorUDPSend {
	private DatagramSocket c_dgSock;
	private DatagramPacket c_dgPack;
	private Person person;
	
	{
		try {
			c_dgSock = new DatagramSocket();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}
	
	public CastorUDPSend(Person person){
		this.person = person;
	}
	
	public CastorUDPSend() {
		super();
	}
	
	public void send(){
		check();
		
		StringWriter sw = new StringWriter();
		try {
			Marshaller.marshal(person, sw);
			
			System.out.println("data is: " + sw.toString());
			
			sendUDP(sw.toString().getBytes());
		} catch (MarshalException e) {
			e.printStackTrace();
		} catch (ValidationException e) {
			e.printStackTrace();
		}
	}
	
	private void sendUDP(byte[] data){
		c_dgPack = new DatagramPacket(data,0,data.length);
		try {
			c_dgPack.setAddress(InetAddress.getLocalHost());
			c_dgPack.setPort(6000);
			
			c_dgSock.send(c_dgPack);
			c_dgSock.close();
			
			System.out.println("已发送Castor成功");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void check(){
		if(c_dgSock==null)
			throw new NullPointerException("CastorUDPSend c_dgSock is null ");
		if(person==null)
			throw new NullPointerException("CastorUDPSend person is null");
	}
	
	public static void main(String[] args) {
		IdentityCard cardId = new IdentityCard();
		cardId.setCardId(612321198611041734L);
		cardId.setAddress("我也不知道！");
		cardId.setBloodType("O型");
		
		Person person = new Person();
		person.setName("张三");
		person.setCardId(cardId);
		
		CastorUDPSend cUDP = new CastorUDPSend(person);
		cUDP.send();
	}
}

